<?php
session_start ();
class Cart_model extends CI_Model {
	public function validate_add_cart_item($id) {
		
		$qty = 1;
		
		$q = $this->db->get_where ( 'products', array ('id' => $id ) );
		
		if ($q->num_rows ()) {
			foreach ( $q->result () as $obj ) {
				$data = array ('id' => $id, 'qty' => $qty, 'price' => $obj->price, 'name' => $obj->name );
			}
			$this->cart->insert ( $data );
			return true;
		} else {
			return false;
		}
	}
	
	public function validate_update_cart_item() {
		try {
			$rowid = $_GET ['rid'];
			$qty = $_GET ['qty'];
			
			$data = array ('rowid' => $rowid, 'qty' => $qty );
			$this->cart->update ( $data );
			return TRUE;
		} catch ( Exception $e ) {
			return FALSE;
		}
	}
	
	public function validate_remove_cart_item() {
		try {
			$rowid = $_GET ['rowid'];
			$qty = $_GET ['quantity'];
			$data = array ('rowid' => $rowid, 'qty' => $qty );
			$this->cart->update ( $data );
			return true;
		} catch ( Exception $e ) {
			return false;
		}
	}
	
	public function validate_checkout($name) {
		$qu = $this->db->get_where ( 'users', array ('username' => $name ) );
		if ($qu->num_rows () < 1) {
			
			return false;
		}
		$u = $qu->row_array ();
		
		$today = date ( "y-m-d H:i:s" );
		
		$data = array ('user_id' => $u ['id'], 'order_date' => $today, 'total_amount' => $this->cart->total (), 'status' => '0', 'shipping' => '210000' );
		
		$this->db->insert ( 'orders', $data );
		
		$quu = $this->db->get_where ( 'orders', array ('user_id' => $u ['id'], 'order_date' => $today ) );
		
		if ($quu->num_rows () < 1) {
			return false;
		}
		$data = $quu->row_array ();
		$order = $data ['id'];
		$_SESSION['order_id']= $order;
		foreach ( $this->cart->contents () as $pro ) {
			
			$data = array ('order_id' => $order, 'product_id' => $pro ['id'], 'quantity' => $pro ['qty'], 'price' => $pro ['price'], 'discount' => '0' );
			$quuu = $this->db->insert ( 'order_details', $data );
		
		}
		
		return true;
	}
	
	public function updateStatus($ses) {	
		$data = array ('status' => '1' );
		
		try {
			$this->db->where ( 'id', $ses );
			$this->db->update ( 'orders', $data );
			unset($ses);
			return true;
		} catch ( Exception $e ) {
			print_r ( $e );
		}
		return false;
	
	}

}